<template>
  <div class="component-two">
    <!-- 选择框区域 -->
    <div class="select-container">
      <el-select v-model="selectedCountry" placeholder="选择国家" @change="handleDataChange">
        <el-option
          v-for="item in countryList"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-select v-model="selectedSport" placeholder="选择项目" @change="handleDataChange">
        <el-option
          v-for="item in sportList"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
    </div>

    <!-- 箱型图 -->
    <div ref="boxplotChart" class="chart-container"></div>

    <!-- 统计数据表格 -->
    <div class="table-container">
      <el-table :data="[distributionData]" border>
        <el-table-column prop="min" label="最小值" />
        <el-table-column prop="25%" label="25%分位数" />
        <el-table-column prop="50%" label="中位数" />
        <el-table-column prop="75%" label="75%分位数" />
        <el-table-column prop="max" label="最大值" />
        <el-table-column prop="mean" label="平均值" />
        <el-table-column prop="std" label="标准差" />
        <el-table-column prop="count" label="样本数" />
      </el-table>
    </div>

    <!-- 性别比例饼图 -->
    <div ref="pieChart" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

// 数据响应式声明
const countryList = ref([])
const sportList = ref([])
const selectedCountry = ref('')
const selectedSport = ref('')
const boxplotChart = ref(null)
const pieChart = ref(null)
const distributionData = ref({})
let boxplotInstance = null
let pieInstance = null

// 获取国家列表
const fetchCountryList = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/select_list_region')
    if (response.data.success) {
      countryList.value = response.data.data
      selectedCountry.value = response.data.data[0]
    }
  } catch (error) {
    console.error('获取国家列表失败：', error)
  }
}

// 获取项目列表
const fetchSportList = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/get_sport_list')
    if (response.data.success) {
      sportList.value = response.data.data
      selectedSport.value = response.data.data[0]
    }
  } catch (error) {
    console.error('获取项目列表失败：', error)
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/olympic_gender', {
      params: {
        country: selectedCountry.value,
        sport: selectedSport.value
      }
    })
    if (response.data.success) {
      updateCharts(response.data)
      distributionData.value = response.data.distribution
    }
  } catch (error) {
    console.error('获取图表数据失败：', error)
  }
}

// 更新箱型图
const updateCharts = (data) => {
  // 更新箱型图
  const boxplotOption = {
    title: {
      text: '运动员年龄分布箱型图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        console.log(params)
        return `${params.name}</br>
                最小值：${params.data[1]}</br>
                25%分位数：${params.data[2]}</br>
                中位数：${params.data[3]}</br>
                75%分位数：${params.data[4]}</br>
                最大值：${params.data[5]}`
      }
    },
    legend: {
      data: ['男性', '女性'],
      top: 30
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%',
      top: '15%'
    },
    xAxis: {
      type: 'category',
      data: [...new Set(data.data.map(item => item.Year))]
    },
    yAxis: {
      type: 'value',
      name: '年龄',
      min: 0,
      max: 100,
      interval: 10,
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '男性',
        type: 'boxplot',
        data: data.data.filter(item => item.Sex === 'M').map(item => [
          item.min,
          item['25%'],
          item['50%'],
          item['75%'],
          item.max
        ]),
        itemStyle: {
          color: '#5470c6',
          borderWidth: 1
        },
        boxWidth: [7, 50],
        emphasis: {
          itemStyle: {
            borderWidth: 2,
            shadowBlur: 5,
            shadowOffsetX: 2,
            shadowOffsetY: 2,
            shadowColor: 'rgba(0,0,0,0.2)'
          }
        }
      },
      {
        name: '女性',
        type: 'boxplot',
        data: data.data.filter(item => item.Sex === 'F').map(item => [
          item.min,
          item['25%'],
          item['50%'],
          item['75%'],
          item.max
        ]),
        itemStyle: {
          color: '#91cc75',
          borderWidth: 1
        },
        boxWidth: [7, 50],
        emphasis: {
          itemStyle: {
            borderWidth: 2,
            shadowBlur: 5,
            shadowOffsetX: 2,
            shadowOffsetY: 2,
            shadowColor: 'rgba(0,0,0,0.2)'
          }
        }
      }
    ]
  }

  // 更新饼图
  const pieOption = {
    title: {
      text: '运动员性别比例',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    legend: {
      orient: 'horizontal',
      top: 30
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: data.proportion.map(([gender, value]) => ({
          name: gender === 'M' ? '男性' : '女性',
          value: value
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  boxplotInstance.setOption(boxplotOption)
  pieInstance.setOption(pieOption)
}

// 处理选择变化
const handleDataChange = () => {
  fetchChartData()
}

// 处理窗口大小变化
const handleResize = () => {
  boxplotInstance?.resize()
  pieInstance?.resize()
}

onMounted(async () => {
  // 初始化图表实例
  boxplotInstance = echarts.init(boxplotChart.value)
  pieInstance = echarts.init(pieChart.value)

  // 获取初始数据
  await fetchCountryList()
  await fetchSportList()
  await fetchChartData()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理图表实例和事件监听
  boxplotInstance?.dispose()
  pieInstance?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.component-two {
  padding: 20px;
}

.select-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
  margin: 20px 0;
}

.table-container {
  margin: 20px 0;
}
</style>
